<template>
	<hyb-page title="商品订单">
		<template v-slot:top>
			<view class="gui-padding gui-bg-white">
				<!-- 搜索框 -->
				<view class="search-container">
					<view class="search-box">
						<text class="search-icon">🔍</text>
						<input class="search-input" v-model="searchKeyword" placeholder="模糊搜索订单号、名称、收货人、手机号"
							@confirm="handleSearch" maxlength="50" />
						<text v-if="searchKeyword" class="clear-icon" @tap="clearSearch">✕</text>
						<text class="search-btn" @tap="handleSearch">搜索</text>
					</view>
				</view>

				<gui-switch-navigation textAlign="center" :isCenter="true" activeDirection="center" :size="0"
					:margin="20" padding="20rpx" :currentIndex="currentIndex" :items="tabs" @change="navchange">
				</gui-switch-navigation>
			</view>
		</template>

		<template v-slot:body>
			<view style="height: 180rpx;"></view>
			<!-- 添加下拉刷新和上拉加载更多 -->
			<scroll-view scroll-y="true" @scrolltolower="loadMore" @refresherrefresh="onRefresh"
				:refresher-enabled="true" :refresher-triggered="refreshing" style="height: calc(100vh - 180rpx);">

				<view style="padding-bottom: 0;" class="gui-order gui-bg-white gui-dark-bg-level-3"
					v-if="items.length>0" v-for="(order, oIndex) in items" :key="oIndex">
					<view
						class="gui-flex gui-space-between gui-align-items-center gui-border-b gui-padding-bottom-small">
						<text class="gui-order-number gui-color-gray">订单号：{{order.out_trade_no}}</text>
						<view class="order-status-section">
							<text class="gui-order-status gui-color-red">{{order.o_status}}</text>
							<text v-if="order.is_transferred" class="transfer-status gui-color-orange">已转让</text>
						</view>
					</view>
					<!-- 转让状态显示 -->
					<view v-if="order.is_transferred"
						class="gui-flex gui-align-items-center gui-padding-y-mini gui-margin-x-small">
						<view class="transfer-info">
							<text class="gui-color-orange gui-text-small">🔄 转让订单</text>
							<view class="transfer-details">
								<text class="gui-color-gray gui-text-small">原管理员ID：{{order.is_transferred}}</text>
								<text v-if="order.receiver_u_id"
									class="gui-color-blue gui-text-small">接收者ID：{{order.receiver_u_id}}</text>
							</view>
						</view>
					</view>
					<!-- 循环展示订单 -->
					<view v-for="(shop, indexShop) in order.shangjia" :key="indexShop" class="gui-border-b"
						@tap="toDetail(order)">
						<!-- 合并后只渲染每种商品一次 -->
						<view class="gui-order-goods gui-flex gui-margin-top" v-for="(goods, indexGoods) in shop.goods"
							:key="indexGoods">
							<view class="gui-order-goods-img">
								<gui-image class="gui-border-radius" :src="goods.g_thumb" :width="120"
									:height="120"></gui-image>
							</view>
							<view class="gui-flex1">
								<view class="gui-flex gui-space-between">
									<text
										class="gui-order-goods-name gui-secondary-text gui-margin-x">{{goods.g_name}}</text>
								</view>
								<!-- 规格列表 -->
								<view v-for="(spec, specIdx) in goods.expanded ? goods.specs : goods.specs.slice(0, 2)"
									:key="specIdx" style="margin-left:20rpx;">
									<text v-if="spec.o_guige_name"
										class="gui-order-goods-guige gui-color-gray gui-margin-x-small gui-text-small">
										规格：{{spec.o_guige_name}}
									</text>
									<text class="gui-order-goods-price gui-color-grey" style="margin-left: 20rpx;">
										￥{{parseFloat(spec.o_price).toFixed(2)}} x {{spec.o_count}}
									</text>
								</view>
								<!-- 如果规格超过2个，显示展开/收起按钮 -->
								<view v-if="goods.specs.length > 2" style="margin-left:20rpx; margin-top: 5rpx;">
									<text class="gui-color-blue gui-text-small" @tap.stop="toggleSpecs(goods)">
										{{goods.expanded ? '收起' : `查看全部${goods.specs.length}个规格`}}
									</text>
								</view>
								<!-- 其他费用信息 -->
								<view v-if="goods.extra1_name" style="margin-left:20rpx; margin-top: 10rpx;">
									<view v-for="(item, index) in goods.extra1_name.split('\n')" :key="index"
										class="gui-flex gui-align-items-center" style="margin-bottom: 5rpx;">
										<text class="gui-color-blue gui-margin-x-small gui-text-small">
											{{item}}
										</text>
										<text v-if="goods.extra1_tip && index === 0"
											class="gui-color-blue gui-icons gui-text-small" style="margin-left: 10rpx;"
											@tap.stop="showTip('其他费用说明', goods.extra1_tip)">
											&#xe646;
										</text>
									</view>
								</view>
								<!-- 增值费用信息 -->
								<view v-if="goods.extra2_name" style="margin-left:20rpx; margin-top: 10rpx;">
									<view v-for="(item, index) in goods.extra2_name.split('\n')" :key="index"
										class="gui-flex gui-align-items-center" style="margin-bottom: 5rpx;">
										<text class="gui-color-green gui-margin-x-small gui-text-small">
											{{item}}
										</text>
										<text v-if="goods.extra2_tip && index === 0"
											class="gui-color-green gui-icons gui-text-small" style="margin-left: 10rpx;"
											@tap.stop="showTip('增值费用说明', goods.extra2_tip)">
											&#xe646;
										</text>
									</view>
								</view>
								<view v-if="goods.zz_money > 0" class="gui-color-red gui-margin-x-small gui-text-small"
									style="margin-left:30rpx;">
									增值费用：{{parseFloat(goods.zz_money).toFixed(2)}}
								</view>
								<view class="gui-flex gui-justify-content-end">
									<text class="gui-order-goods-price gui-color-grey">
										<template v-if="goods.o_yunfei == 0 || goods.o_yunfei === '0.00'">免运费</template>
										<template v-else>运费：￥{{parseFloat(goods.o_yunfei).toFixed(2)}}</template>
									</text>
								</view>
							</view>
						</view>
						<view v-if="order.extra">
							<view v-if="order.extra.truck_num">车牌号：
								<text class="gui-color-gray gui-margin-x-small gui-text-small">{{order.extra.truck_num}}
								</text>
							</view>
							<view v-if="order.extra.bill_num">提货单：
								<text class="gui-color-gray gui-margin-x-small gui-text-small">{{order.extra.bill_num}}
								</text>
							</view>
						</view>
						<view class="gui-flex gui-justify-content-end">
							<text class="gui-order-goods-price ">
								总价：￥{{parseFloat(order.o_money).toFixed(2)}}
							</text>
						</view>
					</view>
					<view class="gui-flex gui-justify-content-end gui-border-t gui-margin-top-small"
						style="gap: 20rpx;padding: 20rpx 0 0;flex-wrap: wrap;">
						<!-- 申请退款按钮 - 转让过的订单不允许退款 -->
						<view v-if="tag == 'yh' && order.o_status == '待收货' && !order.is_transferred"
							@tap="refund(order)" class="order-action-btn order-action-btn-orange">
							申请退款
						</view>
						<!-- 取消订单按钮 - 转让过的订单不允许取消 -->
						<view v-if="tag == 'yh' && order.o_status == '未付款' && !order.is_transferred"
							@tap="cancel(order)" class="order-action-btn order-action-btn-gray">
							取消订单
						</view>
						<!-- 确认收货按钮 -->
						<view v-if="tag == 'yh' && order.o_status == '待收货'" @tap="refund1(order, false)"
							class="order-action-btn order-action-btn-blue">
							确认收货
						</view>
						<!-- 评价按钮 -->
						<view v-if="tag == 'yh' && order.o_status == '待评价'" @tap="goToPingjia(order)"
							class="order-action-btn order-action-btn-green">
							评价
						</view>
						<!-- 确认交易按钮 - 给用户加积分 -->
						<view
							v-if="$store.state.base.uniacid == 48 && (tag == 'sj' || tag == 'manage') && (order.o_status == '待发货' || order.o_status == '待收货')"
							@tap="confirmOrderFinish(order)" class="order-action-btn order-action-btn-green">
							确认交易
						</view>
						<!-- 支付按钮 -->
						<view v-if="tag == 'yh' && order.o_status == '未付款'" @tap="pay(order)"
							class="order-action-btn order-action-btn-blue">
							支付
						</view>
						<!-- 打印按钮 -->
						<view v-if="$store.state.base.show_base.sp_dy &&  tag == 'sj'" @tap="print(order)"
							class="order-action-btn order-action-btn-blue">
							打印
						</view>
						<!-- 发货按钮 -->
						<view v-if="tag == 'sj' && order.o_status == '待发货'" @tap="express(order)"
							class="order-action-btn order-action-btn-blue">
							发货
						</view>
						<!-- 扫码领单功能 - 只有未转让的待发货订单才显示 -->
						<view v-if="$store.state.base.uniacid == 58 &&  tag == 'yh' && order.o_status != '已取消' && order.o_status != '已完成' && 
						((userinfo && userinfo.is_admin == 1) || !order.is_transferred)" @tap="lingdan(order.out_trade_no)"
							class="order-action-btn order-action-btn-blue">
							扫码领单
						</view>
						<!-- 订单转让按钮 - 只有管理员或订单所有者且未转让的订单才显示 -->
						<!-- <view v-if="$store.state.base.uniacid == 58 &&  tag == 'yh' && order.o_status != '已取消' && order.o_status != '已完成' && 
						((userinfo && userinfo.is_admin == 1) || !order.is_transferred)"
						@tap="transferOrder(order)" class="order-action-btn order-action-btn-blue">
						订单转让
					</view> -->


						<view v-if="tag=='yh' && (order.o_status == '待发货' || order.o_status == '待收货') "
							@tap="qrcode(order)" class="order-action-btn order-action-btn-blue">
							扫码核销
						</view>
					</view>
				</view>

				<!-- 加载更多提示 -->
				<view v-if="loading" class="gui-text-center gui-padding">
					<text class="gui-color-gray">加载中...</text>
				</view>
				<view v-if="noMore" class="gui-text-center gui-padding">
					<text class="gui-color-gray">没有更多数据了</text>
				</view>

				<hyb-empty v-if="items.length === 0 && !loading"></hyb-empty>
			</scroll-view>

			<!-- 发货信息弹窗 -->
			<gui-modal ref="popup" :customClass="['gui-bg-white', 'gui-dark-bg-level-3', 'gui-border-radius']"
				title="发货信息">
				<template v-slot:content>
					<view class=" gui-margin">
						<view class="gui-form-item gui-border-b gui-padding">
							<text class="gui-form-label gui-secondary-text">快递名称</text>
							<view class="gui-form-body">
								<input type="text" class="gui-form-input" v-model="express.kuaidi_name"
									placeholder="请输入快递名称" />
							</view>
						</view>

						<view class="gui-form-item gui-border-b gui-padding">
							<text class="gui-form-label gui-secondary-text">快递单号</text>
							<view class="gui-form-body">
								<input type="text" class="gui-form-input" v-model="express.kuaidi_sn"
									placeholder="请输入快递单号" />
							</view>
						</view>
					</view>
				</template>

				<!-- 利用 flex 布局 可以放置多个自定义按钮哦  -->
				<template v-slot:btns>
					<view class="gui-padding">
						<hyb-button label="确认发货" @tap="expressSubmit"></hyb-button>
					</view>
				</template>
			</gui-modal>

			<!-- 价格输入弹窗 - 从hyb-price组件提取 -->
			<gui-modal ref="pricePopup" :customClass="['gui-bg-white', 'gui-dark-bg-level-3', 'gui-border-radius']"
				:title="priceTitle">
				<template v-slot:content>
					<view class="gui-margin gui-padding gui-bg-gray gui-border-b gui-border-radius">
						<input v-model="priceMoney" :placeholder="'请输入' + (pricePlaceholder || priceTitle)"
							:type="priceInputType" />
					</view>
				</template>

				<!-- 利用 flex 布局 可以放置多个自定义按钮哦  -->
				<template v-slot:btns>
					<view class="gui-padding">
						<button type="default" @tap="confirmPrice" class="gui-button-mini gui-bg-blue gui-color-white">
							确认
						</button>
					</view>
				</template>
			</gui-modal>

			<hyb-popup-input tip="请输入退款理由" :min-length="2" @comfirm="comfirmRefund" title="申请退款"
				placeholder="请输入退款理由,最少2个字" ref="popInput"></hyb-popup-input>

			<!-- 海报生成组件 -->
			<hyb-poster ref="poster"></hyb-poster>

			<gui-popup ref="popup1" z-index="8888" :canCloseByShade="false">

				<view class="gui-padding gui-flex gui-justify-content-center gui-color-white">
					请扫码核销
				</view>
				<view class="gui-flex gui-justify-content-center">
					<image style="width: 500rpx; height: auto;border-radius: 20rpx;" mode="widthFix" :src="src"></image>
				</view>

				<view class="gui-flex gui-justify-content-center" style="margin-top: 80rpx;">
					<text @tap="close()" class="gui-icons gui-color-white" style="font-size: 50rpx;">&#xe78a;</text>
				</view>
			</gui-popup>
		</template>

		<!-- 手机号输入弹窗 -->
		<!-- 删除gui-modal，改用uni.showModal -->
	</hyb-page>


</template>

<script>
	export default {
		data() {
			return {
				tag: "yh",
				items: [],
				tabs: [{
						name: '全部'
					}, {
						name: '未付款'
					},
					{
						name: '待发货'
					}, {
						name: '待收货'
					},
					{
						name: '待评价'
					}, {
						name: '已完成'
					}
				],
				currentIndex: 0, // 当前选中的标签索引
				o_status: '',
				express: {
					out_trade_no: "",
					kuaidi_name: "",
					kuaidi_sn: "",
					o_status: "已发货"
				},
				currentItem: null,
				loading: false, // 加载状态
				noMore: false, // 没有更多数据
				refreshing: false, // 刷新状态
				page: 1, // 当前页码
				pageSize: 10, // 每页数量
				transferPhone: '',
				transferOrderObj: null,
				// 价格弹窗相关数据
				priceTitle: "金额",
				pricePlaceholder: "",
				priceMoney: "",
				priceMax: 0,
				priceData: {},
				priceInputType: 'text', // 新增：价格输入框的类型
				userinfo: null, // 添加用户信息
				searchKeyword: '', // 搜索关键词
				needRefresh: false, // 是否需要刷新数据
				src: null,
			}
		},
		onLoad(options) {
			if (options.tag) {
				this.tag = options.tag;
			}

			// 先获取用户信息，再处理其他逻辑
			this.getUserInfo();

			// 处理扫码领单逻辑
			if (options.tag === 'ld' && options.order_id) {
				console.log('扫码领单模式，订单ID:', options.order_id);

				// 显示扫码领单提示
				uni.showToast({
					title: '正在处理扫码领单...',
					icon: 'loading',
					duration: 2000
				});

				// 延迟处理，给微信足够时间完成自动授权
				setTimeout(() => {
					this.waitForUserInfoAndLingdan(options.order_id);
				}, 1000);
			}

			// 监听评价成功事件
			uni.$on('pingjia_success', this.handlePingjiaSuccess);

			this.query();
		},

		onShow() {
			// 页面显示时，检查是否需要刷新数据
			if (this.needRefresh) {
				this.query(true);
				this.needRefresh = false;
			}
		},

		onUnload() {
			// 组件销毁时清理loading状态
			uni.hideLoading();
			// 移除事件监听器
			uni.$off('pingjia_success', this.handlePingjiaSuccess);
		},
		onHide() {
			// 页面隐藏时清理loading状态
			uni.hideLoading();
		},
		methods: {
			qrcode(order) {
				this.src = 'https://xjz.cyygkj.cn/api/qrcode?text=goods_' + order.out_trade_no + '&token=' + uni.storage
					.get(
						"token") + '&margin=1&size=600'
				this.$refs.popup1.open()
			},

			close() {
				this.$refs.popup1.close()
				this.query(true)
			},

			// 处理评价成功事件
			handlePingjiaSuccess(data) {
				// 设置刷新标志，在页面显示时刷新
				this.needRefresh = true;

				// 强制刷新订单数据，重置分页
				this.page = 1;
				this.items = [];
				this.noMore = false;
				this.query(true);

				// 显示刷新提示
				uni.showToast({
					title: '数据已刷新',
					icon: 'success',
					duration: 1000
				});
			},

			// 等待用户信息加载完成后执行领单
			waitForUserInfoAndLingdan(orderId) {
				// 安全验证：订单ID格式
				if (!orderId || typeof orderId !== 'string') {
					console.error('订单ID无效:', orderId);
					uni.showModal({
						title: '参数错误',
						content: '订单ID参数无效',
						showCancel: false
					});
					return;
				}

				// 安全验证：订单ID格式
				if (!/^[a-zA-Z0-9_-]+$/.test(orderId)) {
					console.error('订单ID格式不正确:', orderId);
					uni.showModal({
						title: '参数错误',
						content: '订单ID格式不正确，只能包含数字、字母、下划线、横线',
						showCancel: false
					});
					return;
				}

				// 安全验证：订单ID长度
				if (orderId.length > 50) {
					console.error('订单ID长度超限:', orderId.length);
					uni.showModal({
						title: '参数错误',
						content: '订单ID长度不能超过50个字符',
						showCancel: false
					});
					return;
				}

				const maxWaitTime = 15000; // 最大等待15秒
				const checkInterval = 200; // 每200ms检查一次
				let waitTime = 0;

				const checkUserInfo = () => {
					if (this.userinfo && this.userinfo.u_id) {
						console.log('用户信息已加载，开始执行领单逻辑');
						// 延迟执行领单，确保页面完全加载
						setTimeout(() => {
							this.handleLingdan(orderId);
						}, 500);
					} else if (waitTime < maxWaitTime) {
						waitTime += checkInterval;
						setTimeout(checkUserInfo, checkInterval);
					} else {
						console.log('等待用户信息超时，尝试自动重新获取用户信息');
						// 不跳转登录页面，而是尝试重新获取用户信息
						this.retryGetUserInfo(orderId);
					}
				};

				checkUserInfo();
			},

			// 重试获取用户信息
			async retryGetUserInfo(orderId) {
				try {
					console.log('尝试重新获取用户信息...');
					// 强制重新获取用户信息
					await this.getUserInfo();

					// 再次检查用户信息
					if (this.userinfo && this.userinfo.u_id) {
						console.log('重新获取用户信息成功，执行领单逻辑');
						setTimeout(() => {
							this.handleLingdan(orderId);
						}, 500);
					} else {
						console.log('重新获取用户信息失败，使用延迟重试策略');
						// 使用延迟重试策略，等待微信自动授权
						this.delayedLingdanRetry(orderId);
					}
				} catch (error) {
					console.error('重试获取用户信息失败:', error);
					// 使用延迟重试策略
					this.delayedLingdanRetry(orderId);
				}
			},

			// 延迟重试领单策略
			delayedLingdanRetry(orderId) {
				console.log('启动延迟重试策略，等待微信自动授权...');

				// 显示友好的提示
				uni.showToast({
					title: '正在处理扫码领单...',
					icon: 'loading',
					duration: 2000
				});

				// 延迟重试，给微信足够时间完成自动授权
				setTimeout(() => {
					if (this.userinfo && this.userinfo.u_id) {
						console.log('延迟重试成功，执行领单逻辑');
						this.handleLingdan(orderId);
					} else {
						console.log('延迟重试失败，继续等待...');
						// 继续等待，直到用户信息可用
						this.waitForUserInfoAndLingdan(orderId);
					}
				}, 3000); // 等待3秒后重试
			},

			// 打开价格输入弹窗
			openPricePopup() {
				this.priceTitle = "追加尾款";
				this.pricePlaceholder = "请输入追加金额";
				this.priceMoney = "";
				this.priceMax = 0;
				this.priceInputType = "number"; // 数字输入
				this.priceData = {
					fa_id: 1, // 示例数据
					fa_fwmoney: 100
				};
				this.$refs.pricePopup.open();
			},

			// 确认价格输入
			confirmPrice() {
				// 检查是否是转让操作
				if (this.priceData.type === 'transfer') {
					this.confirmTransfer();
					return;
				}

				// 原有的价格确认逻辑
				let val = parseFloat(this.priceMoney);
				if (this.priceMax == 0 && val < 0) {
					uni.showToast({
						title: "不能小于0",
						icon: 'none'
					});
					return;
				} else if (this.priceMax > 0 && Math.abs(val) > this.priceMax) {
					uni.showToast({
						title: "必须小于" + this.priceMax,
						icon: 'none'
					});
					return;
				} else {
					this.$refs.pricePopup.close();
					this.handlePriceConfirm(this.priceData, val);
				}
			},

			// 处理价格确认
			handlePriceConfirm(data, money) {
				console.log('价格确认:', data, money);
				// 这里可以调用后端API处理价格确认逻辑
				uni.showToast({
					title: "操作成功",
				});
				setTimeout(() => {
					this.query(1);
				}, 1500);
			},

			comfirmRefund(val) {
				uni.gPost("goods/order/save", {
					refund_reason: val,
					out_trade_no: this.currentItem.out_trade_no,
					o_status: '待退款'
				}).then((flag) => {
					this.query(true); // 刷新数据
				})
			},


			cancel(order) {
				console.log(order)
				uni.gPost("goods/order/save", {
					out_trade_no: order.out_trade_no,
					o_status: '已取消'
				}).then((flag) => {
					this.query(true); // 刷新数据
				})
			},

			refund1(order, flag) {
				console.log(order)
				if (flag) {
					// 退款逻辑
					uni.gPost("goods/order/save", {
						tag: this.tag, // 需要传递tag进行权限验证
						out_trade_no: order.out_trade_no,
						o_status: '已退款'
					}).then((flag) => {
						this.query(true); // 刷新数据
					})
				} else {
					// 确认收货逻辑
					uni.gPost("goods/order/save", {
						tag: this.tag, // 需要传递tag进行权限验证
						out_trade_no: order.out_trade_no,
						o_status: '待评价'
					}).then((flag) => {
						uni.showToast({
							title: '确认收货成功',
							icon: 'success'
						});
						this.query(true); // 刷新数据
					}).catch((err) => {
						uni.showToast({
							title: err.message || '确认收货失败',
							icon: 'none'
						});
					});
				}
			},

			// 跳转到评价页面
			goToPingjia(order) {
				console.log('跳转到评价页面，订单:', order);

				// 构建商品信息字符串，包含商品名称和规格
				let goodsInfo = '';
				if (order.shangjia && order.shangjia.length > 0) {
					order.shangjia.forEach(shop => {
						if (shop.goods && shop.goods.length > 0) {
							shop.goods.forEach(goods => {
								goodsInfo += goods.g_name;
								if (goods.specs && goods.specs.length > 0) {
									goodsInfo += ' (' + goods.specs.map(spec => spec.o_guige_name).join(
										', ') + ')';
								}
								goodsInfo += '; ';
							});
						}
					});
				}

				// 编码商品信息，避免URL过长或特殊字符问题
				const encodedGoodsInfo = encodeURIComponent(goodsInfo.trim());

				// uni.navigateTo({
				// 	url: `/hyb_o2o/addpages/pages/pingjia/pingjia?order_id=${order.out_trade_no}&type=goods&goods_info=${encodedGoodsInfo}`
				// });
			},

			// 确认交易功能 - 给用户加积分
			confirmOrderFinish(order) {
				uni.showModal({
					title: "确认交易",
					content: "确认完成交易并给用户加积分吗？",
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '处理中...'
							});

							// 构建分佣列表
							const commissionList = [];

							// 遍历订单中的所有商品
							if (order.shangjia && order.shangjia.length > 0) {
								order.shangjia.forEach(shop => {
									if (shop.goods && shop.goods.length > 0) {
										shop.goods.forEach(goods => {
											// 为每个商品添加分佣信息
											commissionList.push({
												g_id: goods.g_id,
												bind_phone: goods.g_phone || ''
											});
										});
									}
								});
							}

							console.log('分佣列表:', commissionList);

							uni.gPost("goods/confirmOrderFinish", {
								order_id: order.out_trade_no,
								commission_list: commissionList
							}).then((res) => {
								uni.hideLoading();
								uni.showToast({
									title: "交易完成",
									icon: 'success'
								});
								this.query(true); // 刷新数据
							}).catch((err) => {
								uni.hideLoading();
								uni.showToast({
									title: err.message || "操作失败",
									icon: 'none'
								});
							});
						}
					}
				});
			},




			// 扫码领单功能
			lingdan(orderId) {
				console.log('生成扫码领单二维码，订单ID:', orderId);

				// 安全验证：订单ID格式
				if (!orderId || typeof orderId !== 'string') {
					uni.showToast({
						title: '订单ID无效',
						icon: 'none'
					});
					return;
				}

				// 安全验证：订单ID格式
				if (!/^[a-zA-Z0-9_-]+$/.test(orderId)) {
					uni.showToast({
						title: '订单ID格式不正确',
						icon: 'none'
					});
					return;
				}

				// 安全验证：订单ID长度
				if (orderId.length > 50) {
					uni.showToast({
						title: '订单ID长度超限',
						icon: 'none'
					});
					return;
				}

				// #ifdef MP
				// 微信小程序：生成小程序二维码
				const mpPath = "/hyb_o2o/subpagesA/pages/order/order?tag=ld&order_id=" + orderId;
				const mpQrUrl = "https://xjz.cyygkj.cn/api/mp/qrcode?uniacid=" + uni.getStorageSync("uniacid") +
					"&path=" + encodeURIComponent(mpPath);

				console.log('小程序路径:', mpPath);
				console.log('二维码API链接:', mpQrUrl);

				// 生成小程序二维码
				uni.downloadFile({
					url: mpQrUrl,
					success: ((res) => {
						uni.previewImage({
							urls: [res.tempFilePath]
						})
					}),
					fail: (err) => {
						console.error('二维码下载失败:', err);
						uni.showToast({
							title: '二维码生成失败',
							icon: 'none'
						});
					}
				})
				// #endif

				// #ifdef H5
				// H5环境：生成小程序路径二维码
				const h5Path = "/hyb_o2o/subpagesA/pages/order/order?tag=ld&order_id=" + orderId;

				console.log('H5环境小程序路径:', h5Path);

				// 如果有海报组件，使用海报生成
				if (this.$refs.poster) {
					const items = [{
							type: "text",
							text: "扫码领单",
							size: 18,
							align: "center",
							x: 150,
							y: 35
						},
						{
							type: "qrcode",
							text: h5Path,
							x: 50,
							y: 70,
							width: 200
						}
					];

					this.$refs.poster.make(items).then((src) => {
						uni.previewImage({
							urls: [src]
						})
					}).catch((err) => {
						console.error('海报生成失败:', err);
						uni.showToast({
							title: '海报生成失败',
							icon: 'none'
						});
					})
				} else {
					uni.showToast({
						title: 'H5环境需要海报组件支持',
						icon: 'none'
					});
				}
				// #endif
			},

			// 处理扫码领单逻辑
			handleLingdan(orderId) {
				console.log('开始处理扫码领单:', orderId);
				console.log('当前用户信息:', this.userinfo);

				// 安全验证：订单ID格式
				if (!orderId || typeof orderId !== 'string') {
					console.error('订单ID无效:', orderId);
					uni.showModal({
						title: '参数错误',
						content: '订单ID参数无效',
						showCancel: false
					});
					return;
				}

				// 安全验证：订单ID格式
				if (!/^[a-zA-Z0-9_-]+$/.test(orderId)) {
					console.error('订单ID格式不正确:', orderId);
					uni.showModal({
						title: '参数错误',
						content: '订单ID格式不正确，只能包含数字、字母、下划线、横线',
						showCancel: false
					});
					return;
				}

				// 安全验证：订单ID长度
				if (orderId.length > 50) {
					console.error('订单ID长度超限:', orderId.length);
					uni.showModal({
						title: '参数错误',
						content: '订单ID长度不能超过50个字符',
						showCancel: false
					});
					return;
				}

				// 检查用户是否已登录
				if (!this.userinfo || !this.userinfo.u_id) {
					uni.showModal({
						title: "登录提示",
						content: "请先登录后再进行扫码领单操作",
						showCancel: false,
						success: () => {
							// 跳转到登录页面
							uni.navigateTo({
								url: '/hyb_o2o/login/login'
							});
						}
					});
					return;
				}



				uni.showModal({
					title: "确认领单",
					content: `确认要领取订单 ${orderId} 吗？\n\n注意：这将转让订单所有权给当前用户`,
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '正在处理领单请求...'
							});

							// 准备API参数
							const apiParams = {
								order_id: orderId,
								user_phone: this.userinfo.u_phone || '',
								user_name: this.userinfo.u_name || ''
							};

							console.log('领单API参数:', apiParams);
							console.log('订单ID类型:', typeof orderId);
							console.log('订单ID值:', orderId);
							console.log('当前用户信息:', this.userinfo);

							// 调用领单API
							uni.gPost("goods/order/lingdan", apiParams).then((res) => {
								console.log('领单API响应:', res);
								uni.hideLoading();

								if (res && res.data) {
									uni.showToast({
										title: `领单成功！更新了${res.data.updated_records_count || 0}条记录`,
										icon: 'success',
										duration: 3000
									});

									// 刷新订单数据
									setTimeout(() => {
										this.query(true);
									}, 1000);
								} else {
									uni.showToast({
										title: '领单成功，但返回数据异常',
										icon: 'none'
									});
								}
							}).catch((err) => {
								console.error('领单API调用失败:', err);
								uni.hideLoading();

								// 检查是否需要重新载入页面（用户未登录）
								if (err && err.data && err.data.need_reload) {
									console.log('检测到用户未登录，自动重新载入页面');
									uni.showModal({
										title: '需要登录',
										content: '检测到您未登录，正在重新载入页面...',
										showCancel: false
									});

									// 延迟重新载入，让用户看到提示
									setTimeout(() => {
										// 重新载入页面
										uni.reLaunch({
											url: '/hyb_o2o/subpagesA/pages/order/order'
										});
									}, 1500);
									return;
								}

								let errorMsg = '领单失败';
								let errorContent = '可能的原因：\n1. 订单不存在\n2. 订单已被领取\n3. 网络连接问题\n4. 服务器异常';

								if (err && err.message) {
									errorMsg = err.message;
									// 针对特定错误给出友好提示
									if (err.message.includes('不能领取自己的订单')) {
										errorContent =
											'这是您自己的订单，不能领取。\n\n扫码领单功能用于转让订单给其他用户，您需要扫描其他用户的订单二维码。';
									} else if (err.message.includes('订单状态不允许领单')) {
										errorContent = '订单状态不允许领单。\n\n只有"待发货"状态的订单才能被领取。';
									} else if (err.message.includes('订单已被转让')) {
										errorContent = '订单已被转让。\n\n该订单已经被其他用户领取过了。';
									} else if (err.message.includes('订单不存在')) {
										errorContent = '订单不存在。\n\n请检查订单ID是否正确，或者订单可能已被删除。';
									}
								} else if (err && err.errMsg) {
									errorMsg = err.errMsg;
								}

								uni.showModal({
									title: '领单失败',
									content: `错误信息：${errorMsg}\n\n${errorContent}`,
									showCancel: false
								});
							});
						}
					}
				});
			},

			pay(order) {
				console.log(order)
				uni.showActionSheet({
					itemList: ["余额支付", "微信支付"],
					success: (res) => {
						uni.$pay.pay("pay/goods", {
							out_trade_no: order.out_trade_no,
						}, res.tapIndex).then(() => {
							this.query(true); // 刷新数据
						})
					}
				})


			},

			print(item) {

				uni.showModal({
					title: "确定打印",
					content: "确认小票?",
					success: (res) => {
						if (res.confirm) {
							uni.gPost("goods/order/print", {
								out_trade_no: item.out_trade_no
							}).then(() => {
								setTimeout(() => {
									uni.showToast({
										title: '已提交打印！',
										icon: 'none'
									})

								}, 10)
								this.query(true); // 刷新数据
							})
						}
					}
				})




			},
			refund(item) {
				// 检查是否为转让订单
				if (item.is_transferred) {
					uni.showToast({
						title: "转赠订单不允许申请退款",
						icon: 'none'
					});
					return;
				}

				this.currentItem = item;
				this.$refs.popInput.open();
			},
			expressSubmit() {
				console.log(this.express)

				if (this.express.kuaidi_name.trim().length == 0) {
					uni.showToast({
						title: "请输入快递名称",
						icon: "none"
					})
				} else if (this.express.kuaidi_sn.trim().length == 0) {
					uni.showToast({
						title: "请输入快递单号",
						icon: "none"
					})
				} else {
					uni.gPost("goods/order/save", this.express).then((items) => {
						this.query(true); // 刷新数据
						this.$refs.popup.close();
						uni.showToast({
							title: "发货成功"
						})
					})
				}
			},
			fa(item) {
				this.express.out_trade_no = item.out_trade_no;
				this.express.kuaidi_name = "";
				this.express.kuaidi_sn = "";
				this.$refs.popup.open();
			},
			express(item) {
				this.express.out_trade_no = item.out_trade_no;
				this.express.kuaidi_name = "";
				this.express.kuaidi_sn = "";
				this.$refs.popup.open();
			},
			toDetail(order) {
				uni.navigateTo({
					url: '/hyb_o2o/subpagesA/pages/detail/detail?id=' + order.out_trade_no + '&tag=' + this.tag
				});
			},
			navchange(index) {
				this.currentIndex = index;
				if (index == 0) {
					this.o_status = '';
				} else if (index == 1) {
					this.o_status = '未付款';
				} else if (index == 2) {
					this.o_status = '待发货';
				} else if (index == 3) {
					this.o_status = '待收货';
				} else if (index == 4) {
					this.o_status = '待评价';
				} else if (index == 5) {
					this.o_status = '已完成';
				}
				this.query(true);
			},
			transferOrder(order) {
				console.log('transferOrder called, tag:', this.tag);
				this.transferOrderObj = order;
				// 使用价格输入弹窗替代uni.showModal
				this.openTransferPopup();
			},
			// 打开订单转让弹窗
			openTransferPopup() {
				this.priceTitle = "订单转让";
				this.pricePlaceholder = "请输入接收用户的手机号";
				this.priceMoney = "";
				this.priceMax = 0;
				this.priceInputType = "text"; // 文本输入
				this.priceData = {
					out_trade_no: this.transferOrderObj.out_trade_no,
					type: 'transfer' // 标识这是转让操作
				};
				this.$refs.pricePopup.open();
			},
			// 确认转让
			confirmTransfer() {
				const phone = this.priceMoney.trim();

				if (!phone || phone === '') {
					uni.showToast({
						title: "请输入手机号",
						icon: 'none'
					});
					return;
				}

				// 简单的手机号验证
				const phoneRegex = /^1[3-9]\d{9}$/;
				if (!phoneRegex.test(phone)) {
					uni.showToast({
						title: "请输入正确的手机号",
						icon: 'none'
					});
					return;
				}

				this.$refs.pricePopup.close();
				this.submitTransferPhone(phone);
			},
			submitTransferPhone(phone) {
				uni.showLoading({
					title: '转让中...'
				});

				uni.gPost("goods/order/transfer_by_phone", {
					out_trade_no: this.transferOrderObj.out_trade_no,
					phone: phone
				}).then((res) => {
					uni.hideLoading();
					uni.showToast({
						title: "转让成功",
						icon: 'success'
					});
					this.query(true); // 刷新数据
				}).catch((err) => {
					uni.hideLoading();
					uni.showToast({
						title: err.message || "转让失败",
						icon: 'none'
					});
				});
			},
			format_money(money) {
				return parseFloat(money || 0).toFixed(2);
			},
			query(refresh = false) {
				if (refresh) {
					this.page = 1;
					this.items = [];
					this.noMore = false;
				}

				if (this.loading || this.noMore) {
					return;
				}

				this.loading = true;

				const params = {
					tag: this.tag,
					page: this.page,
					pageSize: this.pageSize
				};

				if (this.o_status) {
					params.o_status = this.o_status;
				}

				// 添加搜索参数
				if (this.searchKeyword && this.searchKeyword.trim()) {
					params.search = this.searchKeyword.trim();
				}

				uni.gPost("goods/order/list", params).then((res) => {
					this.loading = false;

					// 后端直接返回数组，不是包含data字段的对象
					const orderList = res || [];

					// 处理订单数据，合并同商品的多规格
					const processedOrders = orderList.map(order => {
						// 处理每个商家下的商品
						if (order.shangjia && order.shangjia.length > 0) {
							order.shangjia.forEach(shop => {
								if (shop.goods && shop.goods.length > 0) {
									// 按商品ID分组，合并同商品的多规格
									const goodsMap = {};
									shop.goods.forEach(goods => {
										const g_id = goods.g_id;
										if (!goodsMap[g_id]) {
											goodsMap[g_id] = {
												...goods,
												specs: [],
												expanded: false // 默认收起
											};
										}

										// 添加规格信息
										goodsMap[g_id].specs.push({
											o_guige_name: goods.o_guige_name,
											o_price: goods.o_price,
											o_count: goods.o_count,
											o_money: goods.o_money
										});
									});

									// 转换为数组
									shop.goods = Object.values(goodsMap);
								}
							});
						}
						return order;
					});

					if (refresh) {
						this.items = processedOrders;
					} else {
						this.items = [...this.items, ...processedOrders];
					}

					this.page++;
					this.noMore = orderList.length < this.pageSize; // 判断是否还有更多数据

					// 重置刷新状态
					if (refresh) {
						this.refreshing = false;
					}
				}).catch((err) => {
					console.error('获取订单列表失败:', err);
					this.refreshing = false;
					this.loading = false;
					this.noMore = false;
				});
			},
			loadMore() {
				this.query();
			},
			onRefresh() {
				this.refreshing = true;
				this.query(true);
			},
			toggleSpecs(goods) {
				goods.expanded = !goods.expanded;
			},
			showTip(title, content) {
				// 检查内容是否为跳转链接
				if (content && content.trim()) {
					// 检查路径是否以 / 开头，如果没有则添加
					let jumpPath = content.trim();
					if (!jumpPath.startsWith('/')) {
						jumpPath = '/' + jumpPath;
					}

					// 进行页面跳转
					uni.navigateTo({
						url: jumpPath,
						fail: (err) => {
							console.error('页面跳转失败:', err);
							uni.showToast({
								title: '页面跳转失败',
								icon: 'none'
							});
						}
					});
				} else {
					// 如果没有跳转路径，显示提示
					uni.showToast({
						title: '暂无相关页面',
						icon: 'none'
					});
				}
			},
			getUserInfo() {
				try {
					const userinfo = uni.storage.get("userinfo");
					console.log('从storage获取用户信息:', userinfo);

					if (userinfo && userinfo.u_id) {
						this.userinfo = userinfo;
						console.log('用户信息设置成功:', this.userinfo);
						return true;
					} else {
						console.warn('用户信息不存在或无效:', userinfo);
						this.userinfo = null;

						// 如果是扫码领单，尝试静默获取用户信息，不强制跳转登录
						if (this.tag === 'ld') {
							console.log('扫码领单模式，尝试静默获取用户信息...');
							// 不显示登录弹窗，让系统自动处理
						}
						return false;
					}
				} catch (error) {
					console.error('获取用户信息失败:', error);
					this.userinfo = null;
					return false;
				}
			},

			// 搜索相关方法
			handleSearch() {
				this.query(true); // 刷新数据
			},

			clearSearch() {
				this.searchKeyword = '';
				this.query(true); // 刷新数据
			}
		}
	}
</script>

<style>
	/* 搜索框样式 */
	.search-container {
		margin-bottom: 20rpx;
	}

	.search-box {
		display: flex;
		align-items: center;
		background-color: #f5f5f5;
		border-radius: 25rpx;
		padding: 10rpx 20rpx;
		position: relative;
	}

	.search-icon {
		font-size: 28rpx;
		color: #999;
		margin-right: 15rpx;
	}

	.search-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		background: transparent;
		border: none;
		outline: none;
	}

	.clear-icon {
		font-size: 24rpx;
		color: #999;
		padding: 5rpx;
	}

	.search-btn {
		font-size: 28rpx;
		color: #007aff;
		padding: 10rpx 20rpx;
		background-color: #f0f0f0;
		border-radius: 20rpx;
		margin-left: 15rpx;
	}

	.header {
		padding: 15rpx 30rpx;
		height: 100rpx;
	}

	.gui-order {
		padding: 25rpx;
		margin: 25rpx;
		margin-bottom: 0rpx;
		border-radius: 10rpx;
	}

	.gui-order-number {
		line-height: 50rpx;
		font-size: 26rpx;
		width: 300rpx;
		flex: 1;
	}

	.gui-shop {
		line-height: 88rpx;
		font-size: 28rpx;
		font-weight: bold;
	}

	.gui-order-goods {
		flex-direction: row;
		flex-wrap: nowrap;
		padding-bottom: 20rpx;
		align-items: flex-start;
	}

	.gui-order-goods-img {
		width: 120rpx;
		height: 120rpx;
	}

	.gui-order-goods-name {
		line-height: 40rpx;
		width: 200rpx;
		flex: 1;
		overflow: hidden;
		font-size: 26rpx;
		margin-left: 20rpx;
		margin-right: 20rpx;
	}

	.gui-order-goods-price {
		font-size: 24rpx;
		line-height: 50rpx;
		text-align: right;
	}

	.gui-order-footer {
		margin-top: 2px;
	}

	.gui-order-status {
		line-height: 50rpx;
		font-size: 26rpx;
		width: 100rpx;
		text-align: center;
	}

	.gui-order-btn {
		width: 150rpx;
		height: 50rpx;
		line-height: 50rpx;
		font-size: 22rpx;
		text-align: center;
		border-radius: 60rpx;
	}

	/* 订单操作按钮样式 */
	.order-action-btn {
		display: inline-block;
		padding: 8rpx 20rpx;
		font-size: 24rpx;
		border-radius: 25rpx;
		border: 1rpx solid;
		text-align: center;
		margin-left: 15rpx;
		min-width: 120rpx;
	}

	.order-action-btn-blue {
		background-color: #165DFF;
		color: #FFFFFF;
		border-color: #165DFF;
	}

	.order-action-btn-green {
		background-color: #00B42A;
		color: #FFFFFF;
		border-color: #00B42A;
	}

	.order-action-btn-orange {
		background-color: #FF7D00;
		color: #FFFFFF;
		border-color: #FF7D00;
	}

	.order-action-btn-gray {
		background-color: #F2F3F5;
		color: #86909C;
		border-color: #E5E6EB;
	}

	/* 价格弹窗相关样式 */
	.gui-button-mini {
		height: 60rpx;
		line-height: 60rpx;
		font-size: 26rpx;
		padding: 0 20rpx;
		border-radius: 30rpx;
		display: inline-block;
		text-align: center;
	}

	.gui-bg-blue {
		background-color: #165DFF;
	}

	.gui-color-white {
		color: #FFFFFF;
	}

	.gui-bg-gray {
		background-color: #F7F8FA;
	}

	.gui-border-radius {
		border-radius: 16rpx;
	}

	.gui-border-b {
		border-bottom: 1rpx solid #F2F3F5;
	}

	.gui-margin {
		margin: 20rpx;
	}

	.gui-padding {
		padding: 20rpx;
	}

	.gui-padding-y {
		padding-top: 20rpx;
		padding-bottom: 20rpx;
	}

	.gui-padding-x {
		padding-left: 20rpx;
		padding-right: 20rpx;
	}

	.gui-padding-y-small {
		padding-top: 10rpx;
		padding-bottom: 10rpx;
	}

	.gui-margin-top {
		margin-top: 20rpx;
	}

	.gui-margin-bottom {
		margin-bottom: 20rpx;
	}

	.gui-text-center {
		text-align: center;
	}

	.gui-h6 {
		font-size: 32rpx;
		font-weight: bold;
	}

	.gui-color-black {
		color: #1D2129;
	}

	.gui-color-gray {
		color: #86909C;
	}

	.gui-text-small {
		font-size: 24rpx;
	}

	.gui-line-height {
		line-height: 1.6;
	}

	.pay-card-radius {
		border-radius: 16rpx;
	}

	/* 添加缺失的样式类 */
	.gui-order-status-text {
		font-size: 22rpx;
		color: #666;
		margin-left: 10rpx;
	}

	.gui-color-green {
		color: #00B42A;
	}

	.gui-color-grey {
		color: #86909C;
	}

	.gui-color-red {
		color: #F53F3F;
	}

	.gui-color-blue {
		color: #165DFF;
	}

	.gui-margin-left {
		margin-left: 30rpx;
	}

	.gui-margin-x-small {
		margin-left: 10rpx;
		margin-right: 10rpx;
	}

	.gui-margin-top-small {
		margin-top: 10rpx;
	}

	.gui-margin-top {
		margin-top: 20rpx;
	}

	.gui-flex1 {
		flex: 1;
	}

	.gui-flex {
		display: flex;
	}

	.gui-row {
		flex-direction: row;
	}

	.gui-space-between {
		justify-content: space-between;
	}

	.gui-align-items-center {
		align-items: center;
	}

	.gui-justify-content-end {
		justify-content: flex-end;
	}

	.gui-border-b {
		border-bottom: 1rpx solid #F2F3F5;
	}

	.gui-border-t {
		border-top: 1rpx solid #F2F3F5;
	}

	.gui-bg-white {
		background-color: #FFFFFF;
	}

	.gui-dark-bg-level-3 {
		background-color: #F7F8FA;
	}

	.gui-primary-text {
		color: #1D2129;
	}

	.gui-secondary-text {
		color: #4E5969;
	}

	/* 转让信息样式 */
	.transfer-info {
		background: #FFF7E6;
		border: 1rpx solid #FFD666;
		border-radius: 8rpx;
		padding: 15rpx;
		width: 100%;
	}

	.transfer-details {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
		margin-top: 8rpx;
	}

	.transfer-details text {
		display: block;
	}

	/* 订单状态区域样式 */
	.order-status-section {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		gap: 5rpx;
	}

	.transfer-status {
		font-size: 20rpx;
		background: #FFF7E6;
		color: #FA8C16;
		padding: 4rpx 8rpx;
		border-radius: 4rpx;
		border: 1rpx solid #FFD666;
	}
</style>